﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.BusinessLogic.Product;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.Orm.View;
using System.Linq;

namespace OpenSoftStore.Client.UIL.ManageProduct
{
    public partial class ProductList : UserControl
    {
        private const string _ShopId = "b0def1a7-bf25-45f2-b65a-6dc586dbfc2c";
        private static ProductList instance;
        private static ProductLogic productBll;
        private static TreeLogic treeBll;
        private static ComboLogic comboBll;
        public V_Product productView;
        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static ProductList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ProductList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        private ProductList()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            productBll = new ProductLogic();
            treeBll = new TreeLogic();
            comboBll = new ComboLogic();

            SPACommon.SetDataGridStyle(dgvProduct);
            SPACommon.SetDataGridStyle(dgvStore);
            SPACommon.SetDataGridStyle(dgvStoreItem);
            LoadControlData();

            btnTree_Add.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理商品分类);
            btnTree_Update.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理商品分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理商品分类);
            tsbAdd.Visible = SysPowerManager.IsHavePower(SysPowerManager.添加商品);
            tsbUpdate.Visible = SysPowerManager.IsHavePower(SysPowerManager.修改商品信息);
            tsbDelete.Visible = SysPowerManager.IsHavePower(SysPowerManager.删除商品);
            tsbInput.Visible = SysPowerManager.IsHavePower(SysPowerManager.商品入库);
            tsbOut.Visible = SysPowerManager.IsHavePower(SysPowerManager.商品出库);
            tsbTransfer.Visible = SysPowerManager.IsHavePower(SysPowerManager.库存调拨);
            tsbStoreSet.Visible = SysPowerManager.IsHavePower(SysPowerManager.仓库设置);
        }

        private void tsbAdd_Click(object sender, EventArgs e)
        {
            ProductAddWindow productAddWindow = new ProductAddWindow();
            productAddWindow.SetTreeValue(tvProduct.SelectedNode.Name, tvProduct.SelectedNode.Text);
            productAddWindow.ShowDialog();
        }

        public void LoadControlData()
        {
            treeBll.SetTreeNode(treeBll.GetProductTree(), tvProduct);
            treeBll.SetTreeNode(treeBll.GetStoreTree(), tvStore);

            tvProduct.ExpandAll();
            tvStore.ExpandAll();

            tvProduct.SelectedNode = tvProduct.Nodes[0];
            SPACommon.SetTreeStyle(tvProduct);
            tvStore.SelectedNode = tvStore.Nodes[0];
            SPACommon.SetTreeStyle(tvStore);

            colPos.ValueMember = "Value1";
            colPos.DisplayMember = "DisplayText";
            var comboList = comboBll.GetComboByBuzType("Pos", _ShopId);
            colPos.DataSource = comboList;

            dgvProduct.AutoGenerateColumns = false;
            dgvProduct.DataSource = productBll.GetProductDataTable();

            GenerateColumnText(comboList);

            dgvStore.AutoGenerateColumns = false;
            dgvStore.DataSource = productBll.GetStoreList();

            dgvStoreItem.AutoGenerateColumns = false;
            dgvStoreItem.DataSource = productBll.GetStoreItemList();

            cmbProvider.DisplayMember = "Name";
            cmbProvider.ValueMember = "Id";
            cmbProvider.DataSource = productBll.GetProvider();

            cmbProvider2.DisplayMember = "Name";
            cmbProvider2.ValueMember = "Id";
            cmbProvider2.DataSource = productBll.GetProvider();


            cmbStore.ValueMember = "Value1";
            cmbStore.DisplayMember = "DisplayText";
            cmbStore.Items.Insert(0, new T_Combo { DisplayText = "库存总和", Value1 = "Store" });
            var comboItems = comboBll.GetComboByBuzType("Pos", _ShopId).ToList();
            cmbStore.Items.AddRange(comboItems.ToArray());
            cmbStore.SelectedIndex = 0;

            cmbStoreNum.ValueMember = "Value1";
            cmbStoreNum.DisplayMember = "DisplayText";
            cmbStoreNum.DataSource = comboBll.GetComboByBuzType("Operator", _ShopId);

            ShopLogic.BindShop(cmbShop);
            ShopLogic.BindShop(cmbShop2);

            dgvStoreItem.DefaultCellStyle.NullValue = comboItems[0].DisplayText;

        }

        public void GenerateColumnText(IEnumerable<T_Combo> comboList)
        {
            foreach (var item in comboList)
            {
                switch (item.Value1)
                {
                    case "Store1":
                        colStore1.HeaderText = item.DisplayText;
                        break;
                    case "Store2":
                        colStore2.HeaderText = item.DisplayText;
                        break;
                    case "Store3":
                        colStore3.HeaderText = item.DisplayText;
                        break;
                    case "Store4":
                        colStore4.HeaderText = item.DisplayText;
                        break;
                    default:
                        break;
                }
            }
        }

        public void BtnSearch_Click(object sender, EventArgs e)
        {
            string treeCode = "";
            if (tvProduct.SelectedNode != null)
            {
                treeCode = tvProduct.SelectedNode.Tag.ToString();
            }
            string condition = "";
            if (cbStore.Checked)
            {
                string store = ((T_Combo)cmbStore.SelectedItem).Value1;
                string compare = ((T_Combo)cmbStoreNum.SelectedItem).Value1;
                if (store == "Store")
                {
                    store = "(Store1+Store2+Store3+Store4)";
                }
                condition = string.Format(" and {0}{1}{2}", store, compare, numAmount.Value);
            }
            string providerName = cmbProvider.Text;
            string productWhere = txtWhere.Text;
            string whereStr = string.Format(
                "  and  T.Code like '{0}%' and  prov.Name like '{1}%'  " +
                " and (P.Name like '{2}%' or  P.Model like '{2}%' or P.Specification like '{2}%' or P.ProductNo like '{2}%') "
                , treeCode, providerName, productWhere);
            whereStr += condition;
            dgvProduct.DataSource = productBll.GetProductDataTable(whereStr);
            lblProductCount.Text = dgvProduct.RowCount.ToString();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabProduct.SelectedIndex == 0)
            {
                BtnSearch_Click(null, null);
            }
            else
            {
                btnQuery_Click(null, null);
                //dgvStoreItem.DataSource = productBll.GetStoreItemList();
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvProduct.SelectedRows.Count == 0)
            {
                return;
            }

            string id = dgvProduct.SelectedRows[0].Cells["Id"].Value.ToString();
            int count = productBll.Where<T_ServiceWithProduct>(s => s.ProductId == id).Count();
            if (count > 0)
            {
                FormSysMessage.ShowMessage("该产品已经被服务引用，不能删除！");
                return;
            }

            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                if (dgvProduct.SelectedRows.Count > 0)
                {
                    var product = new T_Product { Id = id };
                    productBll.DeleteProduct(product);
                    BtnSearch_Click(null, null);
                }
            }

        }


        private void BtnSave_Click(object sender, EventArgs e)
        {

        }

        private void tvProduct_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (tvProduct.SelectedNode.Tag == null) return;
            BtnSearch_Click(null, null);
        }

        private void tsbInput_Click(object sender, EventArgs e)
        {
            ProductInputWindow productInputWindow = new ProductInputWindow();
            productInputWindow.Show();
        }

        private void tsbOut_Click(object sender, EventArgs e)
        {
            ProductOutWindow productOutWindow = new ProductOutWindow();
            productOutWindow.Show();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ProductAddWindow productAddWindow = new ProductAddWindow();
            productAddWindow.ShowDialog();
        }


        private void btnProvider_Click(object sender, EventArgs e)
        {

        }

        private void tsbTransfer_Click(object sender, EventArgs e)
        {
            ProductTransferWindow productTransferWindow = new ProductTransferWindow();
            productTransferWindow.Show();
        }

        private void tsbConfirmInput_Click(object sender, EventArgs e)
        {

        }

        private void tsbDel_Click(object sender, EventArgs e)
        {
            if (dgvStore.SelectedRows.Count != 0)
            {
                if (MessageBox.Show("确定要撤销吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {

                    string storeId = dgvStore.SelectedRows[0].Cells["StoreId"].Value.ToString();
                    var store = productBll.Where<T_StoreIO>(s => s.Id == storeId).FirstOrDefault();
                    var storeItems = productBll.Where<T_StoreIOItem>(s => s.StoreIOId == storeId).ToList();
                    if (store.Type == "入库")
                    {
                        foreach (var item in storeItems)
                        {
                            V_StoreIOItem view = new V_StoreIOItem();
                            view.Pos2 = item.Pos;
                            view.ProductId = item.ProductId;
                            view.Amount = item.Amount;
                            productBll.StoreOut(view);
                        }
                    }
                    else
                    {
                        foreach (var item in storeItems)
                        {
                            V_StoreIOItem view = new V_StoreIOItem();
                            view.Pos = item.Pos;
                            view.ProductId = item.ProductId;
                            view.Amount = item.Amount;
                            productBll.StoreInput(view);
                        }
                    }

                    productBll.DeleteStoreIO(storeId);
                    dgvStore.DataSource = productBll.GetStoreList();
                    dgvStoreItem.DataSource = productBll.GetStoreItemList();
                }
            }
        }

        private void dgvStore_SelectionChanged(object sender, EventArgs e)
        {
            dgvStoreItem.DataSource = null;
            if (dgvStore.SelectedRows.Count > 0)
            {
                string id = dgvStore.SelectedRows[0].Cells["StoreId"].Value.ToString();

                dgvStoreItem.AutoGenerateColumns = false;
                dgvStoreItem.DataSource = productBll.GetStoreItemList(" where S.StoreIOId='" + id + "'");
                lblStoreItemCount.Text = dgvStoreItem.RowCount.ToString();
            }
        }

        private void tsbStoreSet_Click(object sender, EventArgs e)
        {
            StoreSetWindow storeSetWindow = new StoreSetWindow();
            storeSetWindow.ShowDialog();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string providerName = cmbProvider2.Text;
            DateTime from = dtpFrom.Value.Date;
            DateTime to = dtpTo.Value.Date.AddDays(1);
            string treeNames = string.Join(",", treeBll.GetStoreTree(tvStore.SelectedNode.Tag.ToString()).Select(m => "'" + m.Name + "'").ToArray());
            dgvStore.DataSource = productBll.GetStoreList(string.Format(" where S.BuzType in (" + treeNames + ")  and P.Name='{0}' and S.AddTime between #{1}# and #{2}#  Order By S.AddTime desc", providerName, from, to));
            lblStoreCount.Text = dgvStore.RowCount.ToString();
            if (dgvStore.Rows.Count > 0)
            {
                dgvStore_SelectionChanged(null, null);
            }
            else
            {
                dgvStoreItem.DataSource = null;
                lblStoreItemCount.Text = dgvStoreItem.RowCount.ToString();
            }
        }

        private void tvStore_AfterSelect(object sender, TreeViewEventArgs e)
        {
            btnQuery_Click(null, null);
            
        }

        private void tvProduct_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (tvProduct.SelectedNode == null) return;
            tvProduct.SelectedNode.EndEdit(true);
            treeBll.SaveTreeNode(tvProduct, sender, e, "ProductTree");
        }

        private void btnTree_Add_Click(object sender, EventArgs e)
        {
            if (tvProduct.SelectedNode == null) return;
            TreeNode tnParent = tvProduct.SelectedNode;
            tvProduct.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };

            tnParent.Nodes.Add(treeNode);
            tvProduct.SelectedNode = treeNode;
            treeNode.BeginEdit();
            dgvProduct.DataSource = null;
        }

        private void btnTree_Update_Click(object sender, EventArgs e)
        {
            if (tvProduct.SelectedNode == null) return;
            tvProduct.LabelEdit = true;
            tvProduct.SelectedNode.BeginEdit();
        }

        private void btnTree_Delete_Click(object sender, EventArgs e)
        {
            if (tvProduct.SelectedNode == null) return;
            string treeCode = tvProduct.SelectedNode.Tag.ToString();
            int count = productBll.GetProductDataTable(" and  T.Code like '" + treeCode + "%'").Rows.Count;
            if (count > 0)
            {
                FormSysMessage.ShowMessage("该节点下仍有数据，不能删除！");
                return;
            }
            else
            {
                treeBll.Delete(tvProduct);
                tvProduct.Select();
            }
        }

        private void BtnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnSearch_Click(null, null);
            }
        }

        private void btnQuery_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BtnSearch_Click(null, null);
            }
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            if (dgvProduct.SelectedRows.Count > 0)
            {
                string id = dgvProduct.SelectedRows[0].Cells["Id"].Value.ToString();
                ProductAddWindow productAddWindow = new ProductAddWindow();
                productAddWindow.GetProduct(id);
                productAddWindow.ShowDialog();
            }
        }

        private void lnkRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            tvProduct_AfterSelect(null, null);
        }

        private void dgvProduct_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            tsbUpdate_Click(null, null);
        }

        private void tsbModify_Click(object sender, EventArgs e)
        {
            if (dgvStore.SelectedRows.Count == 0) return;
            var storeId = dgvStore.SelectedRows[0].Cells["StoreId"].Value.ToString();
            var store = productBll.Where<T_StoreIO>(s => s.Id == storeId).FirstOrDefault();

            if (store.BuzType == "进货" || store.BuzType == "调拨调入" || store.BuzType == "盘盈")
            {
                ProductInputWindow productInputWindow = new ProductInputWindow();
                productInputWindow.GetStoreIO(store);
                productInputWindow.ShowDialog();
            }
            else if (store.BuzType == "耗材" || store.BuzType == "调拨调出" || store.BuzType == "向供应商退货" || store.BuzType == "盘亏")
            {
                ProductOutWindow productOutWindow = new ProductOutWindow();
                productOutWindow.GetStoreIO(store);
                productOutWindow.ShowDialog();
            }
            else if (store.BuzType == "仓库调出" || store.BuzType == "仓库调入")
            {
                //ProductTransferWindow productTransfer = new ProductTransferWindow();
                //productTransfer.ShowDialog();
            }
        }

        private void dgvStore_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            tsbModify_Click(null, null);
        }
    }
}
